package com.yznote.cloudesk.aop;

import com.yznote.cloudesk.cache.yCache.YCacheCtrl;
import com.yznote.cloudesk.common.Anno.CacheCtrol;
import com.yznote.cloudesk.common.Anno.CacheType;
import com.yznote.cloudesk.common.Anno.Table;
import com.yznote.cloudesk.common.pojo.User;
import com.yznote.cloudesk.common.tokenShare.YTokenShare;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.lang.reflect.Method;

/**
 * 缓存的自动删除
 */
@Aspect
@Component
public class CacheAop {
    @Autowired
    YTokenShare yTokenShare;
    @Autowired
    YCacheCtrl yCacheCtrl;
    @Pointcut("@annotation(com.yznote.cloudesk.common.Anno.CacheCtrol)")
    public void pointcut(){

    }
    // 正常执行接口
    @AfterReturning(pointcut = "pointcut()")
    public void handleCache(JoinPoint jp){
        User user = yTokenShare.get();
        Assert.notNull(user,"user is null,but enter the method");
        // 获得织入的方法
        Method method = ((MethodSignature) jp.getSignature()).getMethod();
        // 获得方法上的缓存注解
        CacheCtrol annotation = method.getAnnotation(CacheCtrol.class);
        // 没有该注解 不使用缓存
        if(annotation==null) return;
        // 处理注解
        // 获得缓存类型
        CacheType type = annotation.type();
        // 查询方法名
        String methodName = method.getName();
        // 获取依赖的表
        Table[] tables = annotation.value();
        String cacheModule = annotation.cacheModule();
        if(type==CacheType.MODIFY){
            boolean saveCache = annotation.saveCache();
            if(!saveCache)yCacheCtrl.delete(user,tables,cacheModule);
            else yCacheCtrl.delete(user,tables,methodName);
        }else{
            // 放置关系
            yCacheCtrl.push(user,methodName,tables);
        }
    }

}
